<template>
    <div>
        <el-card>
            <el-row :gutter="10">
                <div class="search_input">
                    <el-col :span="6">
                        <el-input size="small" placeholder="请输入名称" clearable></el-input>
                    </el-col>
                    <el-col :span="6">
                        <el-input size="small" placeholder="请输入名称" clearable></el-input>
                    </el-col>
                    <el-col :span="6">
                        <el-input size="small" placeholder="请输入名称" clearable></el-input>
                    </el-col>
                    <el-col :span="6">
                        <el-input size="small" placeholder="请输入名称" clearable></el-input>
                    </el-col>
                </div>
                <div class="search_input" v-show="showSearch">
                    <el-col :span="6">
                        <el-input size="small" placeholder="请输入名称" clearable></el-input>
                    </el-col>
                    <el-col :span="6">
                        <el-input size="small" placeholder="请输入名称" clearable></el-input>
                    </el-col>
                    <el-col :span="6">
                        <el-input size="small" placeholder="暂未开通"></el-input>
                    </el-col>
                </div>
                <el-col :span="20">
                    <el-button type="primary" size="small">搜索</el-button>
                    <el-button type="info" size="small">重置</el-button>
                    <el-button type="text" style="margin-left:10px" id="closeSearchBtn" @click="closeSearch">
                        {{ word }}
                        <i :class="showAll ? 'el-icon-arrow-up ': 'el-icon-arrow-down'"></i>
                    </el-button>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="20">
                    <el-tooltip effect="dark" content="刷新" placement="top" :enterable="false">
                        <el-button type="primary" size="small" :icon="icon" @click="getProjectList"></el-button>
                    </el-tooltip>
                    <el-button type="primary" size="small" v-has="'admin/save_project'" @click="addItem">新增项目</el-button>
                </el-col>
            </el-row>
            <el-table :data="projectList" border stripe v-loading="loading"
                      element-loading-text="拼命加载中...."
                      size="small"
                      element-loading-spinner="el-icon-loading">
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column prop="title" label="名称"></el-table-column>
                <el-table-column prop="review_cycle" label="周期"></el-table-column>
                <el-table-column label="是否开始">
                    <template slot-scope="scope">
                        <el-tag @click="iStart(scope.row)" v-if="scope.row.is_start === 0">未开始</el-tag>
                        <el-tag @click="iStart(scope.row)" v-else-if="scope.row.is_start === 1">进行中</el-tag>
                        <el-tag v-else type="success">结束</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.status === 0">未同步</el-tag>
                        <el-tag v-else type="success">已同步</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-tooltip effect="dark" content="编辑" placement="top" :enterable="false">
                            <el-button type="primary" icon="el-icon-edit" v-has="'admin/save_project'" @click="editProject(scope.row.id)" size="mini"
                            ></el-button>
                        </el-tooltip>
                        <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
                            <el-button type="danger" icon="el-icon-delete" v-has="'admin/del_project'" size="mini" @click="delProject(scope.row.id)"
                            ></el-button>
                        </el-tooltip>
                        <el-tooltip effect="dark" content="同步数据" placement="top" v-has="'admin/sync_project_case'" :enterable="false" v-show="scope.row.status === 0">
                            <el-button type="warning" icon="el-icon-s-help" size="mini"
                                       @click="syncProjectDialog(scope.row.id)"
                            ></el-button>
                        </el-tooltip>
                        <el-tooltip effect="dark" content="查看案件" placement="top" :enterable="false" v-show="scope.row.status === 1">
                            <el-button type="success" icon="el-icon-s-cooperation" size="mini"
                                       @click="checkSyncProjectCase(scope.row.id)"
                            ></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryInfo.page"
                    :page-sizes="[10, 20, 30, 40,50]"
                    :page-size="queryInfo.limit"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-card>
        <el-dialog :title="title"
                   ref="dialogComponent"
                   :visible.sync="dialogVisible"
                   @close="dialogClose('ruleForm')"
                   width="50%">
            <el-form :model="projectForm" :rules="projectRules" ref="ruleForm" label-width="100px"
                     class="demo-ruleForm">
                <el-form-item label="项目名称" prop="title">
                    <el-input v-model="projectForm.title" placeholder="请输入项目名称"></el-input>
                </el-form-item>
                <el-form-item label="项目周期" prop="review_cycle">
                    <el-date-picker style="width: 100%"
                            v-model="projectForm.review_cycle"
                            type="month"
                            placeholder="选择月" format="yyyy-MM" value-format="yyyy-MM">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
            <el-button size="small" @click="resetForm('ruleForm')">重 置</el-button>
            <el-button size="small" type="primary" @click="saveProject('ruleForm')">确 定</el-button>
  </span>
        </el-dialog>
        <!-- 同步数据 -->
        <el-dialog title="同步数据"
                   :visible.sync="syncDialogVisible"
                   @close="syncDialogClose('syncRefForm')"
                   width="50%">
            <el-form :model="syncForm" :rules="syncRules" ref="syncRefForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="同步项目" prop="sync_project_id">
                    <el-select v-model="syncForm.sync_project_id" placeholder="请选择同步项目" style="width: 100%" clearable
                               remote filterable :remote-method="remoteMethod" loading-text="正在获取中...."
                               :loading="SelectLoading">
                        <el-option v-for="item in syncProjectList" :index="item.id + ''" :key="item.id"
                                   :label="item.name"
                                   :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="syncDialogVisible = false">取 消</el-button>
        <el-button size="small" type="primary" :loading="btnLoading" @click="saveSyncProject">确 定</el-button>
      </span>
        </el-dialog>

    </div>
</template>

<script>
import axios from "axios";
 import { Loading } from 'element-ui'
export default {
    name: "index",
    data() {
        return {
            showAll: true,
            showSearch: false,
            icon: 'el-icon-refresh',
            dialogVisible: false, //新增and编辑弹出层
            syncDialogVisible: false, //同步数据弹出层
            loading: true,
            SelectLoading: false,
            title: '',
            btnLoading:false,
            //初始化条条件
            queryInfo: {
                title: '',
                limit: this.$global_limit,
                page: this.$global_page
            },
            //总数
            total: 0,
            //数据源
            projectList: [],
            //提交表单
            projectForm: {
                id: 0,
                title: '',
                review_cycle:''
            },
            //认证
            projectRules: {
                title: [
                    {required: true, message: '请输入项目名称', trigger: 'blur'},
                ],
                review_cycle:[
                    {required: true, message: '请输入项目周期', trigger: 'blur'},
                ]
            },
            syncForm: {
                sync_project_id: ''
            },
            syncRules: {
                sync_project_id: [
                    {required: true, message: '请选择项目', trigger: 'change'}
                ],
            },
            syncProjectList: [],
            review_id: 0

        }
    },
    created() {
        this.getProjectList()
    },
    // 页面渲染后调用
    mounted() {
        this.$nextTick(function () {
            this.closeSearch()
        })
    },
    methods: {
        //项目列表
        async getProjectList() {
            const {data: res} = await this.$http.get('admin/project_list', {params: this.queryInfo})
            if (res.code !== 200) return this.$message.error('获取数据失败')
            this.projectList = res.data.list;
            this.total = res.data.totalCount
            this.loading = false
        },
        // 搜索框的展开和关闭
        closeSearch() {
            this.showAll = !this.showAll
            if (this.showAll === false) {
                this.showSearch = false
            } else {
                this.showSearch = true
            }
        },
        handleSizeChange(newSize) {
            this.queryInfo.limit = newSize
            this.getProjectList()
        },
        handleCurrentChange(newPage) {
            this.queryInfo.page = newPage
            this.getProjectList()
        },
        //打开窗口
        addItem() {
            this.projectForm = {
                id: 0,
                title: ''
            };
            this.title = '新增项目';
            this.dialogVisible = true;
            this.$nextTick(() => {
                this.$refs["dialogComponent"].showDialog = true;
            });
        },
        //保存项目
        saveProject(formName) {
            this.$refs[formName].validate(async (valid) => {
                if (!valid) return this.$message.error('输入不合法')
                const {data: res} = await this.$http.post('admin/save_project', this.projectForm)
                if (res.code !== 200) return this.$message.error(res.data.message)

                this.$message.success(this.projectForm.id === 0 ? '新增成功' : '编辑成功')
                this.dialogVisible = false
                await this.getProjectList()
            });
        },
        //重置
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        //编辑项目
        async editProject(id) {
            this.title = '编辑项目';
            this.dialogVisible = true
            this.$nextTick(() => {
                this.$refs["dialogComponent"].showDialog = true;
            });
            //结构赋值
            const {data: res} = await this.$http.get('admin/read_project/' + id)
            if (res.code !== 200) return this.$message.error(res.data.message)

            this.projectForm = res.data.list
        },
        //删除项目
        async delProject(id) {
            const configResult = await this.$confirm('此操作将永久删除该项目, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err);
            if (configResult !== 'confirm') return this.$message.info('已取消删除')
            let loadingInstance = Loading.service({
                text: '小主请稍等片刻,奴家正在玩命删除项目以及对应的案件和样本点中...',
                background: 'rgba(0,0,0,.5)'
            })
            const {data: result} = await this.$http.delete('admin/del_project/' + id)
            if (result.code !== 200) return this.$message.error(result.data.message)
            loadingInstance.close()
            this.$message.success('数据删除成功');
            //删除成功后页码改变返还为上一页
            let totalPage = Math.ceil((this.total - 1) / this.queryInfo.limit);
            let currentPage = this.queryInfo.page > totalPage ? totalPage : this.queryInfo.page;
            this.queryInfo.page = this.queryInfo.page < 1 ? 1 : currentPage;
            await this.getProjectList()
        },
        //关闭弹出窗口
        dialogClose(formName) {
            this.$refs[formName].resetFields();
        },
        async syncProjectDialog(id) {
            this.review_id = id
            this.syncDialogVisible = true
        },
        //数据远程搜索
        remoteMethod() {
            this.SelectLoading = true;
            setTimeout(async () => {
                this.SelectLoading = false;
                const {data: res} = await axios.get('http://chuangcheng.ahamr.cn/project_list')
                if (res.code !== 200) return this.$message.error('获取同步数据失败')
                this.$nextTick(() => {
                    this.syncProjectList = res.data.list
                })
            }, 100);
        },
        syncDialogClose(formName) {
            this.$refs[formName].resetFields();
        },
        //获取项目问卷信息
        async saveSyncProject() {
            const {data: res} = await axios.get(`http://chuangcheng.ahamr.cn/get_city_project/${this.syncForm.sync_project_id}`)
            if (res.code !== 200) return this.$message.error('获取同步数据失败')
             this.btnLoading = true
            //处理同步数据
            await this.syncProjectCase(res.data.list)
        },
        //执行同步数据
        async syncProjectCase(arr) {
            this.$set(arr, 'review_id', this.review_id)
            let loadingInstance = Loading.service({
                text: '小主请稍等片刻,奴家正在玩命处理中...',
                background: 'rgba(0,0,0,.5)'
            })
            const {data: res} = await this.$http.post('admin/sync_project_case', arr)
            if (res.code !== 200) return this.$message.error('数据同步失败');
            this.$nextTick(() => {
                loadingInstance.close()
                this.$message.success('数据同步成功');
                this.getProjectList()
                this.btnLoading = false
                this.syncDialogVisible = false
            })
        },
        //获取项目案件
        checkSyncProjectCase(id){
            sessionStorage.setItem('new_project_id', id)
            this.$router.push({ name: '样本点' })
        },
        async iStart(row){
            let mess;
            if (row.is_start === 0) {
                mess = "此操作把项目设置为进行中,是否继续";
            } else {
                mess = "此操作把项目设置为结束,是否继续";
            }
            const configResult = await this.$confirm(mess, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err);
            if (configResult !== 'confirm') return this.$message.info('已取消操作')
            const {data: result} = await this.$http.get('admin/change_project/' + row.id)
            if (result.code !== 200) return this.$message.error(result.data.message)
            this.$message.success('操作成功')

            await this.getProjectList()
        }
    },
    // 计算属性
    computed: {
        word: function () {
            if (this.showAll === false) {
                //对文字进行处理
                return '展开'
            } else {
                return '收起'
            }
        }
    }
}
</script>

<style scoped>
.ivu-inline-block .ivu-dropdown {
    display: inline-block;
}

.i-link-color, .i-link-color:active, .i-link-color:hover {
    color: inherit;
}

.i-link {
    cursor: pointer;
}

.ivu-fr {
    float: right;
}

.ivu-dropdown-rel {
    position: relative;
}

.ivu-ml {
    margin-right: 16px !important;
}

.ivu-tooltip, .ivu-tooltip-rel {
    display: inline-block;
}

.ivu-tooltip-rel {
    position: relative;
    width: inherit;
}

.el-row {
    margin-bottom: 20px;

}

.prompt {
    background: white;
    width: 100px;
    height: 30px;
    text-align: center;
}

.el-row:last-child {
    margin-bottom: 0;
}


.search-box {
    position: absolute;
    top: 25px;
    left: 120px;
}

.previewImg {
    width: 30%;
}

.amap-page-container {
    position: relative;
}

.search_input .el-col {
    margin-bottom: 10px;
}

#searchBox {
    overflow: hidden;
}

.el-cascader {
    line-height: normal;
}

.inline-block {
    margin-left: 10px;
    display: inline-block;
}

.amap-demo {
    height: 300px;
}
</style>
